<?php


namespace app\app\controller;


use app\model\UserModel;
use Webman\Http\Response;
use support\request;
use app\common\Sign;
use app\common\Verify;

class Login
{
    public function byMobile(request $request){

        if(empty(input('userName',null))){
            return error(0,"userName is null");
        }
        if(empty(input('passWord',null))){
            return error(0,"passWord is null");
        }

        $userModel = new UserModel();
        $user = $userModel->login(input('userName'), input('passWord'));
        if($user instanceof Response){
            return $user;
        }
        else{
            $iat = time();
            $payload = [
                'iss' => config('app.app_name'), //签发者
                'iat' => $iat, //什么时候签发的
                'exp' => $iat + 60*60*24*365, //过期时间()
                'uid' => $user['user_id']
            ];
            $jwt = Sign::encode($payload, config('app.jwt_sign'));
            $user['access_token'] = $jwt;
            return success($user,0,'登录成功');
        }
    }

    public function webLogin(request $request){
        $token = input("token");
        $verify = new Verify(array("seKey"=>$token));
        if ($verify->check(input('code'))) {
            if(empty(input('userName',null))){
                return error(0,"userName is null");
            }
            if(empty(input('passWord',null))){
                return error(0,"passWord is null");
            }

            $userModel = new UserModel();
            $user = $userModel->login(input('userName'), input('passWord'));
            if($user instanceof Response){
                return $user;
            }
            else{
                $iat = time();
                $payload = [
                    'iss' => config('app.app_name'), //签发者
                    'iat' => $iat, //什么时候签发的
                    'exp' => $iat + 60*60*24*365, //过期时间()
                    'uid' => $user['user_id']
                ];
                $jwt = Sign::encode($payload, config('app.jwt_sign'));
                $user['access_token'] = $jwt;
                return success($user,0,'登录成功');
            }
        }
        else{
            return error(1, "验证码错误");
        }
    }

    public function verify(request $request){
        $token = input("token");
        $code = new Verify(array("seKey"=>$token,"imageH"=>"32","imageW"=>"100",'useCurve'=> false,'useNoise'=>false,'length'=>4,'fontSize'=>14,'bg'=>array(213,224,233)));
        $img = $code->entry();
        ob_start();
        imagepng($img);
        $fileContent = ob_get_contents();
        ob_end_clean();
        return response("data:image/png;base64," . base64_encode($fileContent), 200, ['Content-Type' => 'image/jpeg']);
    }
}